package com.lkdont.android.media.examples.ui.video.camera

import android.Manifest
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.lkdont.android.base.ui.BaseFrag
import com.lkdont.android.base.util.Logger
import com.lkdont.android.media.camera.CameraException
import com.lkdont.android.media.camera.CameraVideoRecorder
import com.lkdont.android.media.camera.OldCameraManager
import com.lkdont.android.media.camera.widget.CameraPreviewView
import com.lkdont.android.media.examples.R
import kotlinx.android.synthetic.main.frag_record_camera_video_2.*


/**
 * 录制摄像头视频例子
 *
 * @author lkdont
 */
class RecordCameraVideoFrag2 : BaseFrag() {

    companion object {

        private const val REQ_ID_PERMISSIONS = 101

        private val PERMISSIONS = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.frag_record_camera_video_2, container, false)
    }

    /*** 初始化视频UI */
    private fun initVideoView() {
        videoView.eventListener = object : CameraPreviewView.EventListener {

            override fun onPreviewStart() {
                Logger.d(this, "onPreviewStart: 开始预览")
            }

            override fun onPreviewStop() {
                Logger.d(this, "onPreviewStop: 停止预览")
            }

            override fun onError(e: CameraException) {
                e.printStackTrace()
                showMessage(e.message)
            }
        }
        videoView.recorder = videoRecorder
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 初始化视频UI
        initVideoView()
        // 设置点击事件
        recordBtn.setOnClickListener {
            toggleRecording()
        }
        switchCameraBtn.setOnClickListener {
            switchCamera()
        }
    }

    private var recording = false

    private fun toggleRecording() {
        recording = !recording
        if (recording) {
            videoRecorder.startRecording(
                CameraVideoRecorder.Config(
                    "/sdcard/test-camera-video.mp4",
                    1080,
                    1920,
                    3000000
                )
            )
        } else {
            videoRecorder.stopRecording()
        }
        updateRecordingUi()
    }

    private fun updateRecordingUi() {
        if (recording) {
            recordBtn.text = "停止录制"
        } else {
            recordBtn.text = "开始录制"
        }
    }

    private var selectedCameraId = OldCameraManager.CameraType.BACK_CAMERA.id

    private fun switchCamera() {
        selectedCameraId = if (selectedCameraId == OldCameraManager.CameraType.BACK_CAMERA.id) {
            OldCameraManager.CameraType.FRONT_CAMERA.id
        } else {
            OldCameraManager.CameraType.BACK_CAMERA.id
        }
        updateSwitchCameraBtn()
        // 切换摄像头
        stopPreview()
        startPreview(selectedCameraId)
    }

    private fun updateSwitchCameraBtn() {
        if (selectedCameraId == OldCameraManager.CameraType.BACK_CAMERA.id) {
            switchCameraTv.setText(R.string.back_camera)
        } else {
            switchCameraTv.setText(R.string.front_camera)
        }
    }

    override fun onResume() {
        super.onResume()
        // 开始预览
        startPreview(selectedCameraId)
        // 更新UI
        updateRecordingUi()
        updateSwitchCameraBtn()
    }

    override fun onPause() {
        super.onPause()
        // 停止预览
        stopPreview()
    }

    //******************************** 权限 ********************************//

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQ_ID_PERMISSIONS) {
            if (hasPermissions(PERMISSIONS)) {
                startPreview(selectedCameraId)
            } else {
                showMessage(R.string.no_permission)
            }
        }
    }

    //******************************** 摄像头 ********************************//

    private fun startPreview(cameraId: Int) {
        if (!hasPermissions(PERMISSIONS)) {
            // 没有权限
            requestPermissions(
                PERMISSIONS,
                REQ_ID_PERMISSIONS
            )
            return
        }
        videoView.startPreview(cameraId)
    }

    private fun stopPreview() {
        videoView.stopPreview()
    }

    private val videoRecorder = CameraVideoRecorder()

}